<?php
namespace plugin\ky_black\app\admin\controller;

use support\Request;
use support\Response;
use plugin\ky_black\app\admin\model\Staff;
use plugin\ky_black\app\admin\service\JwtService;

class LoginController
{
    /**
     * @var JwtService
     */
    protected $jwtService;

    public function __construct()
    {
        $this->jwtService = new JwtService();
    }

    /**
     * 管理员登录
     */
    public function login(Request $request): Response
    {
        $username = $request->input('username');
        $password = $request->input('password');

        // 参数验证
        if (empty($username) || empty($password)) {
            return json(['code' => 1, 'msg' => '用户名和密码不能为空']);
        }

        // 查找用户
        $staff = Staff::where('username', $username)->first();
        if (!$staff) {
            return json(['code' => 1, 'msg' => '用户名或密码错误']);
        }

        // 验证密码
        if (!password_verify($password, $staff->password)) {
            return json(['code' => 1, 'msg' => '用户名或密码错误']);
        }

        // 验证状态
        // if ($staff->status !== '1') {
        //     return json(['code' => 1, 'msg' => '账号已被禁用']);
        // }

        // 生成token
        $token = $this->jwtService->createToken([
            'staff_id' => $staff->id,
            'username' => $staff->username
        ]);

        // 返回用户信息
        $userInfo = [
            'staff_id' => $staff->id,
            'username' => $staff->username,
            'role_id' => $staff->role_id
        ];

        return json([
            'code' => 0,
            'msg' => '登录成功',
            'data' => [
                'token' => $token,
                'userInfo' => $userInfo
            ]
        ]);
    }

    /**
     * 获取用户信息
     */
    public function info(Request $request): Response
    {
        // 从请求头获取token
        $token = $request->header('Authorization');
        if (empty($token)) {
            return json(['code' => 401, 'msg' => '未登录']);
        }

        // 验证token
        $payload = $this->jwtService->verifyToken($token);
        if (!$payload) {
            return json(['code' => 401, 'msg' => '登录已过期']);
        }

        // 获取用户信息
        $staff = Staff::find($payload['staff_id']);
        if (!$staff) {
            return json(['code' => 401, 'msg' => '用户不存在']);
        }

        // 返回用户信息
        return json([
            'code' => 0,
            'msg' => '获取成功',
            'data' => [
                'staff_id' => $staff->id,
                'username' => $staff->username,
                'role_id' => $staff->role_id,
                'roles' => ['admin'], // 这里可以根据实际角色返回
                'permissions' => ['*'] // 这里可以根据实际权限返回
            ]
        ]);
    }

    /**
     * 退出登录
     */
    public function logout(Request $request): Response
    {
        // 这里可以添加token黑名单等逻辑
        return json(['code' => 0, 'msg' => '退出成功']);
    }
} 